<template>
  <div class="login-form">
    <div class="text-center text-xxl text-bold sv-text-streamer">
      <i class="sv-icons-vue text-xxl"></i>
      {{ appTitle }}
    </div>
    <div class="login-input">
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" :size="formSize" @keyup.enter.native="toLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" clearable>
            <template #prefix>
              <el-icon class="el-input__icon">
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            autocomplete="new-password"
            clearable
          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="gcaptcha">
          <el-input
            v-model="loginForm.gcaptcha"
            placeholder="请输入图形验证码"
            :maxlength="4"
            spellcheck="false"
            clearable
            class="gcaptcha-input"
          >
            <template #prefix>
              <i class="sv-icons-verify"></i>
            </template>
            <template #append>
              <el-image v-loading="gcaptchaLoading" class="flex-vhc" :src="gcaptchaImg" @click="getGcaptcha"></el-image>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="flex justify-between">
        <el-checkbox v-model="loginForm.rememberme">记住我</el-checkbox>
        <el-button v-if="!isHasAdmin" text size="small" type="primary" @click="toRegisterAdmin">注册管理员账号</el-button>
      </div>
    </div>
    <div class="login-btn">
      <el-button icon="CircleClose" round :size="formSize" @click="reset">重置</el-button>
      <el-button icon="UserFilled" round :size="formSize" type="primary" :loading="btnLoading" @click="toLogin">登录</el-button>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { parseIdentity, sendGraphicsCaptcha } from '@/api/auth'
import { hasAdmin, login } from '@/api/system/user'
import { sayHello } from '@/utils'
import { useAuthStore } from '@/stores/auth'
import { useKeepAliveStore } from '@/stores/keepAlive'
import { useTabsStore } from '@/stores/tabs'
import { HOME_URL } from '@/common/constants/global'
import { ElNotification } from 'element-plus'

const emits = defineEmits(['changeMode'])

const appTitle = import.meta.env.VITE_APP_TITLE

const router = useRouter()
const userStore = useUserStore()
const authStore = useAuthStore()
const keepAliveStore = useKeepAliveStore()
const tabsStore = useTabsStore()

const formSize = 'large' // 固定表单大尺寸
const loginFormRef = ref()
const loginForm = ref({
  username: '',
  password: '',
  gcaptcha: '',
  rememberme: false
})
const loginRules = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  gcaptcha: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }]
})

const gcaptchaImg = ref('')
const gcaptchaLoading = ref(false)

onMounted(() => {
  getGcaptcha()
  getHasAdmin()
  loginForm.value = Object.assign({ ...loginForm.value }, userStore.rememberLoginForm)
})

async function getGcaptcha() {
  gcaptchaLoading.value = true

  const res = await sendGraphicsCaptcha({ type: 'login' })
  gcaptchaImg.value = res.data

  gcaptchaLoading.value = false
  // 置空图形验证码输入框
  loginForm.value.gcaptcha = ''
}

const isHasAdmin = ref(true)
async function getHasAdmin() {
  const res = await hasAdmin()
  isHasAdmin.value = res.data
}

function toRegisterAdmin() {
  emits('changeMode', 'register')
}

function reset() {
  loginFormRef.value.resetFields()
}

const btnLoading = ref(false)

function toLogin() {
  btnLoading.value = true
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await login(loginForm.value)

        // 更新部分缓存
        userStore.userInfo = res.data
        userStore.setRememberLogin(loginForm.value)
        authStore.access_token = res.access_token
        authStore.refresh_token = res.refresh_token

        // 更新身份信息
        const identityRes = await parseIdentity({
          id: userStore.userInfo.id,
          username: userStore.userInfo.username
        })
        authStore.identity = identityRes.data

        // 清空部分缓存
        keepAliveStore.setKeepAlive([])
        tabsStore.setTabs([])

        // 跳转到首页
        router.push(HOME_URL)

        // 提示语
        ElNotification({
          title: sayHello(),
          message: `欢迎登录 ${appTitle}`,
          type: 'success',
          duration: 3000
        })
      } catch (error) {
        // 刷新验证码
        // getGcaptcha()
        console.warn(error)
      } finally {
        btnLoading.value = false
      }
    } else {
      btnLoading.value = false
    }
  })
}
</script>

<style lang="scss" scoped>
.login-form {
  max-width: 420px;
  min-width: 240px;
  padding: 20px;

  .login-input {
    margin: 20px 0;

    .gcaptcha-input {
      cursor: pointer;
      :deep(.el-input-group__append) {
        padding: 0;
        .el-button > span {
          padding: 0 20px !important;
        }
      }
    }
  }

  .login-btn {
    width: 100%;
    display: flex;
    justify-content: space-evenly;

    .el-button {
      width: 185px;
    }
  }
}
</style>
